package com.demo.util;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

/**
 * mq队列推送
 * 
 * @author LiaoMinJun
 *
 */
public class ActiveMQPusher {
	private Logger log = Logger.getLogger(ActiveMQPusher.class);

	private String user;
	private String pwd;
	private String url;
	private String queue;

	public ActiveMQPusher(String i_user, String i_pwd, String i_url, String i_queue) {
		user = i_user;
		pwd = i_pwd;
		url = i_url;
		queue = i_queue;
	}

	public ActiveMQPusher(String i_url, String i_queue) {
		user = ActiveMQConnection.DEFAULT_USER;
		pwd = ActiveMQConnection.DEFAULT_PASSWORD;
		url = i_url;
		queue = i_queue;
	}

	public void push2ActiveMQ(String data) {
		Connection connection = null;
		Session session = null;
		MessageProducer producer = null;
		try {
			ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, pwd, url);
			connection = factory.createConnection();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(queue);
			producer = session.createProducer(destination);
			connection.start();
			TextMessage message = session.createTextMessage(data);
			producer.send(message);
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			if (producer != null) {
				try {
					producer.close();
				} catch (JMSException e) {
					log.error(e.getMessage());
				}
			}
			producer = null;
			if (session != null) {
				try {
					session.close();
				} catch (JMSException e) {
					log.error(e.getMessage());
				}
			}
			session = null;
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					log.error(e.getMessage());
				}
			}
			connection = null;
		}
	}

}
